const dgram = require("dgram");
const server = dgram.createSocket("udp4");
const vote_middle = require("../middle/first_vote_contract");
const config = require("./config.json");
var Web3 = require("web3");
var dns = require("dns");
const to = (promise) => {
  return promise.then((res) => [null, res]).catch((error) => [error]);
};
function resolveHost(domain) {
  return new Promise((resolve, reject) => {
    dns.lookup(domain, function onLookup(err, address, family) {
      if (err) {
        reject(err);
      } else {
        resolve(address);
      }
    });
  });
}
var port = config.vote_listener.port;
server.on("error", (err) => {
  console.log("server error:" + err.stack);
  server.close();
});
server.on("listening", () => {
  const addr = server.address();
  console.log(`run ${addr.address}:${addr.port}`);
});
server.on("message", async (msg, rinfo) => {
  //   收到来自投票发起节点的信息
  var msg2obj = JSON.parse(msg);
  console.log(
    "收到来自%s的投票信息，域名为%s \t合约地址为%s",
    rinfo.address,
    msg2obj.domain,
    msg2obj.contract
  );
  var web3 = new Web3(config.ws_rpc_node);
  var domain = msg2obj.domain;
  var contract_address = msg2obj.contract;
  var vote_contract_abi = JSON.parse(config.vote_contract.abi);
  var account = config.account;
  var password = config.password;
  var vote_contract = new web3.eth.Contract(
    vote_contract_abi,
    contract_address
  );
  [host_err, host_res] = await to(resolveHost(domain));
  if (host_err) {
    console.log("域名解析失败");
  } else {
    [unlock_err, unlock_res] = await to(
      vote_middle.unlock(web3, account, password)
    );
    [err, res] = await to(
      vote_middle.vote(account, vote_contract, domain, host_res)
    );
    if (err) {
      if (err.toString().indexOf("unlock") != -1) {
        await vote_middle.vote(account, vote_contract, domain, host_res);
      } else {
        console.log("参与投票----失败");
        console.log(err);
      }
    } else {
      console.log("参与投票----成功");
      console.log("投票依据：");
      console.log(res);
    }
  }
});
server.bind(port);
